#include <stdio.h>
#include <signal.h>
#include <string.h>

#include "hiredis/hiredis.h"
#include "hiredis/adapters/libuv.h"

static void connectCallback(const redisAsyncContext *ctx, int status) {
    if (status != REDIS_OK){
        printf("Error: %s\n", ctx->errstr);
        return;
    }
    printf("Connected\n");
}

static void disconnectCallback(const redisAsyncContext *ctx, int status) {
    if (status != REDIS_OK){
        printf("Error: %s\n", ctx->errstr);
        return;
    }
    printf("disConnected\n");
}

static void on_reply(redisAsyncContext *ctx, void *r, void *userp) {
    redisReply *reply = (redisReply *)r;
    if (reply == NULL) {
        printf("Error: reply null %s\n", ctx->errstr);
        return;
    }

    if (reply->type == REDIS_REPLY_ERROR) {
        printf("Error: %s\n", reply->str);
        return;
    }

    switch (reply->type) {
        case REDIS_REPLY_STRING:
            printf("%d %s\n", reply->type, reply->str);
            break;
        case REDIS_REPLY_INTEGER:
            printf("%d %lld\n", reply->type, reply->integer);
            break;
        case REDIS_REPLY_ARRAY: {
            for (int i = 0; i < reply->elements; ++i) {
                on_reply(ctx, reply->element[i], userp);
                printf("------------------\n");
            }
        }
            break;
        default:
            break;
    }

}

int main(int argc, const char **argv) {
    signal(SIGPIPE, SIG_IGN);
    uv_loop_t *loop = uv_default_loop();

    redisAsyncContext * ctx = redisAsyncConnect("127.0.0.1", 6381);
    if (ctx->err) {
        printf("Error: %s\n", ctx->errstr);
        return -1;
    }

    redisLibuvAttach(ctx, loop);
    redisAsyncSetConnectCallback(ctx, connectCallback);
    redisAsyncSetDisconnectCallback(ctx, disconnectCallback);
    redisAsyncCommand(ctx, on_reply, nullptr, "get a");
    redisAsyncCommand(ctx, on_reply, nullptr, "CLUSTER slots");
    redisAsyncCommand(ctx, on_reply, nullptr, "hgetall GCDB_ACCOUNT:xcy");
    uv_run(loop, UV_RUN_DEFAULT);


    return 0;
}
